package com.capri.utils;


import com.capri.Constant.Constants;
import com.capri.app.NurseHomeApp;

import java.util.TimeZone;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by liukanshan on 2016/12/8.
 */

public class ServiceFactory {

    private static ServiceFactory instance;

    public static ServiceFactory GetInstance() {
        synchronized (ServiceFactory.class) {
            if (instance == null) {
                instance = new ServiceFactory();
            }
        }
        return instance;
    }

    public <S> S createService(Class<S> serviceClass) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Constants.BASE_URL)
                .client(getOkHttpClient())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        return retrofit.create(serviceClass);
    }

    private OkHttpClient getOkHttpClient() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        //设置超时时间以及App拦截器
        BasicParamsInterceptor paramsInterceptor=
                new BasicParamsInterceptor.Builder()
                        .addHeaderParam("Content-Type", "application/json; charset=utf-8")
                        .addParam("f", "android")
                        .addParam("language", "zh_cn")
                        .addParam("countryCode", "+86")
                        .addParam("version", DeviceUtils.getVersionName())
                        .addParam("appVersion", DeviceUtils.getVersionName())
                        .addParam("phoneId", Constants.DEVICE_ID)
                        .addParam("phoneVersion", DeviceUtils.getDeviceInfo())
                        .addParam("userId",PreferenceUtils.GetUserId())
                        .addParam("token", PreferenceUtils.GetUserToken())
                        .addParam("deviceId",Constants.DEVICE_ID)
                        .addParam("platform","android")
                        .addParam("deviceModel",Constants.DEVICE_MODEL)
                        .addParam("timezone", TimeZone.getDefault().getDisplayName(false, TimeZone.SHORT).replace("GMT","").replace(":",""))
                        .build();
        builder.connectTimeout(10, TimeUnit.SECONDS).writeTimeout(10, TimeUnit.SECONDS).readTimeout(10, TimeUnit.SECONDS).addInterceptor(paramsInterceptor);
        return builder.build();
    }
}
